package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishMapper;
import com.sky.mapper.FlavorMapper;
import com.sky.mapper.SetMealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 *菜品管理
 */
@Service
@Slf4j
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private FlavorMapper flavorMapper;

    @Autowired
    private SetMealDishMapper setMealDishMapper;

    @Autowired
    private SetmealMapper setmealMapper;





    @Override
    @Transactional
    public void saveWithFlavor(DishDTO dishDTO) {

        //向菜品表新增一条数据
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dishMapper.save(dish);
        //上面sava方法执行完成后，生成的id会自动赋值到 dish  对象上去
        Long id = dish.getId();

        //向口味表新增多条或不新增数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors !=null && flavors.size()>0){
            flavors.forEach(dishFlavor -> dishFlavor.setDishId(id));
            flavorMapper.saveBatch(flavors);
        }

    }

    @Override
    public PageResult pageQuery(DishPageQueryDTO queryDTO) {
        PageHelper.startPage(queryDTO.getPage(),queryDTO.getPageSize());
        Page<DishVO> page=dishMapper.pageQuery(queryDTO);
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    @Transactional
    public void deleteBatch(List<Long> ids) {
        //先判断该菜品的状态，起售状态不能删除
        for (Long id : ids) {
            Dish dish=dishMapper.getById(id);
            if (dish.getStatus() == StatusConstant.ENABLE){
                throw  new DeletionNotAllowedException(MessageConstant.SETMEAL_ON_SALE);
            }
        }

        //在判断该菜品是否在套餐中，在的话不能删除
        List<Long> setMealDishIds=setMealDishMapper.getByDishIds(ids);
        if (setMealDishIds!= null && setMealDishIds.size()>0 ){
            throw  new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        //删除菜品
//        for (Long id : ids) {
//            dishMapper.deleteById(id);
//            //删除菜品对应的口味
//            flavorMapper.deleteByDishId(id);
//        }

        //直接批量删除
        dishMapper.deleteBatchById(ids);
        flavorMapper.deleteBatchByDishId(ids);

    }

    @Override
    public DishVO getById(Long id) {
        DishVO dishVO = new DishVO();
        //查询菜品，然后拷贝数据
        Dish dish = dishMapper.getById(id);
        BeanUtils.copyProperties(dish,dishVO);

        //查询菜品对应口味，插入VO中
        List<DishFlavor> dishFlavors= flavorMapper.getByDishId(id);
        dishVO.setFlavors(dishFlavors);

        return dishVO;
    }

    @Override
    public void updateDish(DishDTO dishDTO) {
        //先将dish拷贝出来
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        //修改dish
        dishMapper.update(dish);

        //先根据dishid，删除所有菜品的口味
        Long dishId = dish.getId();
        flavorMapper.deleteByDishId(dishId);

        //再将口味列表获取出来,有值的话，塞上dishid，做新增
        List<DishFlavor> flavors = dishDTO.getFlavors();

        if(flavors!=null && flavors.size()>0){
            flavors.forEach(dishFlavor -> dishFlavor.setDishId(dishId));

            //重新批量新增
            flavorMapper.saveBatch(flavors);
        }

    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = flavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }

    /**
     * 根据分类id查询菜品
     * @param categoryId
     * @return
     */
    public List<Dish> list(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        return dishMapper.list(dish);
    }


    /**
     * 根据菜品id获取其分类id
     * @param dishId
     * @return
     */
    @Override
    public Long getCategoryByDishId(Long dishId) {
        Long categoryId=dishMapper.getCategoryByDishId(dishId);
        return categoryId;
    }

    /**
     * 菜品起售停售
     *
     * @param status
     * @param id
     */
    @Transactional
    public void startOrStop(Integer status, Long id) {
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();
        dishMapper.update(dish);

        if (status == StatusConstant.DISABLE) {
            // 如果是停售操作，还需要将包含当前菜品的套餐也停售
            List<Long> dishIds = new ArrayList<>();
            dishIds.add(id);
            // select setmeal_id from setmeal_dish where dish_id in (?,?,?)
            List<Long> setmealIds = setMealDishMapper.getSetmealIdsByDishIds(dishIds);
            if (setmealIds != null && setmealIds.size() > 0) {
                for (Long setmealId : setmealIds) {
                    Setmeal setmeal = Setmeal.builder()
                            .id(setmealId)
                            .status(StatusConstant.DISABLE)
                            .build();
                    setmealMapper.update(setmeal);
                }
            }
        }
    }
}
